/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cjava.system.bean.meeting;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import org.cjava.system.model.ApertureAssociate;
import org.cjava.system.model.BusinessAssociate;
import org.cjava.system.model.Meeting;
import org.cjava.system.model.MeetingBusinessAssociate;
import org.cjava.system.model.Person;
import org.cjava.system.model.State;
import org.cjava.system.model.Teacher;
import org.cjava.system.service.interfac.IApertureAssociateService;
import org.cjava.system.service.interfac.IBusinessAssociateService;
import org.cjava.system.service.interfac.IMeetingBusinessAssociateService;
import org.cjava.system.service.interfac.IMeetingService;
import org.cjava.system.service.interfac.IStateService;
import org.cjava.system.service.interfac.ITeacherService;
import org.cjava.system.util.Clazz;
import org.cjava.system.util.faces.FacesUtil;
import org.primefaces.model.chart.PieChartModel;

/**
 *
 * @author max
 */
@ManagedBean
@SessionScoped
public class MeetingBean implements Serializable {
private static final long serialVersionUID = 1L;
    // <editor-fold defaultstate="collapsed" desc="SERVICES"> 
    @ManagedProperty("#{teacherService}")
    ITeacherService teacherService;
    @ManagedProperty("#{meetingService}")
    IMeetingService meetingService;
    @ManagedProperty("#{meetingBusinessAssociateService}")
    IMeetingBusinessAssociateService meetingBusinessAssociateService;
    @ManagedProperty("#{stateService}")
    IStateService stateService;
    @ManagedProperty("#{businessAssociateService}")
    IBusinessAssociateService businessAssociateService;
    @ManagedProperty("#{apertureAssociateService}")
    IApertureAssociateService apertureAssociateService;
    @ManagedProperty("#{clazz}")
    Clazz clazz;
    // </editor-fold> 
    // <editor-fold defaultstate="collapsed" desc="Campos de Meeting"> 
////////////////////////////
    private List<Teacher> listTeacher;
    private List<State> listStateMeeting;
    private Teacher teacher = new Teacher();
    ////////////////////////////
    private Meeting meeting = new Meeting();
    ///////////////////////////////////////
    //Para la tabla
    private List<Meeting> listMeeting;
    ////////////////////////////////////////
    private Integer activeForUsers = 1;
// </editor-fold> 

    // <editor-fold defaultstate="collapsed" desc="Campos para la asistencia de alumnos"> 
    private List<MeetingBusinessAssociate> listMeetingBusinessAssociate;
    private PieChartModel pieModel = new PieChartModel();
    // </editor-fold>

    public Integer businessAssociateSelectedId;
    private BusinessAssociate businessAssociate = new BusinessAssociate();
    private MeetingBusinessAssociate meetingBusinessAssociateRemove;
    private ApertureAssociate apertureAssociate = new ApertureAssociate();

    /////////////////////////////////////////////////////////////////////
    public void initValuesForAssistance() throws Exception {
        listMeetingBusinessAssociate = null;
        List<ApertureAssociate> listAp = apertureAssociateService.listHQL("from ApertureAssociate a "
                + "where a.year=" + Calendar.getInstance().get(Calendar.YEAR));
        if (listAp.isEmpty()) {
            apertureAssociate = new ApertureAssociate();
            apertureAssociate.setDescription("Nueva apertura para lo socios del " + Calendar.getInstance().get(Calendar.YEAR));
            apertureAssociate.setPricePerAssociate(BigDecimal.valueOf(50));
            apertureAssociate.setYear(Calendar.getInstance().get(Calendar.YEAR));
            apertureAssociate.setId(apertureAssociateService.save(apertureAssociate));
        } else {
            apertureAssociate = listAp.get(0);
        }
        pieModel.clear();
        int conteoAsistencia = 0;
        for (int i = 0; i < getListMeetingBusinessAssociate().size(); i++) {
            if (listMeetingBusinessAssociate.get(i).getAssistan()) {
                conteoAsistencia++;
            }
        }
        pieModel.set("Asistieron: " + conteoAsistencia, conteoAsistencia);
        pieModel.set("No Asistieron: " + (listMeetingBusinessAssociate.size() - conteoAsistencia), listMeetingBusinessAssociate.size() - conteoAsistencia);
    }

    /**
     * Para cambiar el estado de la asistencia
     *
     * @param metSelected
     */
    public void changeStateAssistance(MeetingBusinessAssociate metSelected) throws Exception {
        if (metSelected.getAssistan()) {
            //Pasar a False
            metSelected.setAssistance(false);
            meetingBusinessAssociateService.update(metSelected);
        } else {
            //Pasar a verdadero
            metSelected.setAssistance(true);
            meetingBusinessAssociateService.update(metSelected);
        }
        initializePieBart();
    }

    public void initializePieBart() throws Exception {
        pieModel.clear();
        int conteoAsistencia = 0;
        for (int i = 0; i < getListMeetingBusinessAssociate().size(); i++) {
            if (listMeetingBusinessAssociate.get(i).getAssistan()) {
                conteoAsistencia++;
            }
        }
        pieModel.set("Asistieron: " + conteoAsistencia, conteoAsistencia);
        pieModel.set("No Asistieron: " + (listMeetingBusinessAssociate.size() - conteoAsistencia), listMeetingBusinessAssociate.size() - conteoAsistencia);
    }

    public List<MeetingBusinessAssociate> getListMeetingBusinessAssociate() throws Exception {
        if (listMeetingBusinessAssociate == null) {
            String hql = "from MeetingBusinessAssociate m "
                    + "where m.idMeeting.id=" + meeting.getId();
            listMeetingBusinessAssociate
                    = meetingBusinessAssociateService.listHQL(hql);
        }
        return listMeetingBusinessAssociate;
    }

    public List<BusinessAssociate> autocompleteSearch(String query) throws Exception {
        System.out.println("Query: " + query);
        query = query.trim().toLowerCase();
        State st = clazz.STATE(Clazz._STATE._NAME._BUSINESS_ASSOCIATE_CARNET_NUEVO, Clazz._STATE._ENTITY._BusinessAssociate);

        String SQL = "select b.* , p.* "
                + "FROM business_associate b, person p where "
                + "p.id=b.id_person and b.id_aperture_associate=(idApertureAssociate) and b.id_state=(idState) and lower(concat(p.father_name,' ',p.mother_name,' ',p.name)) "
                + "like '" + query + "%'";
        SQL = SQL.replace("(idState)", st.getId() + "");
        SQL = SQL.replace("(idApertureAssociate)", apertureAssociate.getId() + "");
        List<Object[]> listTemp = businessAssociateService.listHQL(SQL, 1, null);
        List<BusinessAssociate> listCharged = new ArrayList();
        for (int i = 0; i < listTemp.size(); i++) {
            BusinessAssociate temp = ((BusinessAssociate) listTemp.get(i)[1]);
            temp.setIdPerson((Person) listTemp.get(i)[0]);
            listCharged.add(temp);
        }
        return listCharged;
    }

    public void addAssosiateToMeeting() throws Exception {
        if (businessAssociate != null) {
            MeetingBusinessAssociate meetingBusinessAssociate = new MeetingBusinessAssociate();
            meetingBusinessAssociate.setAssistance(false);
            meetingBusinessAssociate.setComingIn(Calendar.getInstance().getTime());
            meetingBusinessAssociate.setIdBusinessAssociate(businessAssociate);
            meetingBusinessAssociate.setIdMeeting(meeting);
            meetingBusinessAssociateService.save(meetingBusinessAssociate);
            listMeetingBusinessAssociate.add(meetingBusinessAssociate);
            initializePieBart();
        }
    }

    public void deleteMeetingBusinessAssociate() throws Exception {
        meetingBusinessAssociateService.delete(meetingBusinessAssociateRemove);
        FacesUtil.addMessage("Eliminado del evento...", null, FacesMessage.SEVERITY_INFO);
        initValuesForAssistance();
    }

    public void clearDialogData() {
        businessAssociate = new BusinessAssociate();
    }

    public PieChartModel getPieModel() {
        return pieModel;
    }

    // <editor-fold defaultstate="collapsed" desc="Getter  and setter de Asistencia"> 
    public void setListMeetingBusinessAssociate(List<MeetingBusinessAssociate> listMeetingBusinessAssociateYES) {
        this.listMeetingBusinessAssociate = listMeetingBusinessAssociateYES;
    }

    public Integer getBusinessAssociateSelectedId() {
        return businessAssociateSelectedId;
    }

    public MeetingBusinessAssociate getMeetingBusinessAssociateRemove() {
        return meetingBusinessAssociateRemove;
    }

    public void setMeetingBusinessAssociateRemove(MeetingBusinessAssociate meetingBusinessAssociateRemove) {
        this.meetingBusinessAssociateRemove = meetingBusinessAssociateRemove;
    }

    public void setApertureAssociateService(IApertureAssociateService apertureAssociateService) {
        this.apertureAssociateService = apertureAssociateService;
    }

    public BusinessAssociate getBusinessAssociate() {
        return businessAssociate;
    }

    public void setBusinessAssociate(BusinessAssociate businessAssociate) {
        this.businessAssociate = businessAssociate;
    }

    public void setBusinessAssociateSelectedId(Integer businessAssociateSelectedId) {
        this.businessAssociateSelectedId = businessAssociateSelectedId;
    }

    public void setPieModel(PieChartModel pieModel) {
        this.pieModel = pieModel;
    }

    public void setBusinessAssociateService(IBusinessAssociateService businessAssociateService) {
        this.businessAssociateService = businessAssociateService;
    }

    public void setMeetingBusinessAssociateService(IMeetingBusinessAssociateService meetingBusinessAssociateService) {
        this.meetingBusinessAssociateService = meetingBusinessAssociateService;
    }

    // </editor-fold> 
    // <editor-fold defaultstate="collapsed" desc="Todo Meeteing"> 
    /**
     * si hace click en el boton del menu CREAR EVENTO, se crea una nueva
     * instancia del objeto
     */
    public void initValues() {
        listTeacher = null;
        listStateMeeting = null;
        meeting = new Meeting();
    }

    public void initValuesForViewTable() {
        listMeeting = null;

    }

    public void saveOrUpdateMeeting() throws Exception {
        System.out.println("Fecha: " + meeting.getStartDate());
        
        if (meeting.getId() == null) {
//            if (activeForUsers == 1) {
                meeting.setIdState(clazz.STATE(Clazz._STATE._NAME._MEETING_SOLO_SOCIOS, Clazz._STATE._ENTITY._Meeting));
            
//            } else if (activeForUsers == 2) {
//                meeting.setIdState(clazz.STATE(Clazz._STATE._NAME._MEETING_SOCIOS_Y_PERSONAS, Clazz._STATE._ENTITY._Meeting));
//            }

            meetingService.save(meeting);
            FacesUtil.addMessage("Evento Guardado...", null, FacesMessage.SEVERITY_INFO);
            meeting = new Meeting();
        } else {
//            if (activeForUsers == 1) {
                meeting.setIdState(clazz.STATE(Clazz._STATE._NAME._MEETING_SOLO_SOCIOS, Clazz._STATE._ENTITY._Meeting));
//            } else if (activeForUsers == 2) {
//                meeting.setIdState(clazz.STATE(Clazz._STATE._NAME._MEETING_SOCIOS_Y_PERSONAS, Clazz._STATE._ENTITY._Meeting));
//            }
            meetingService.update(meeting);
            FacesUtil.addMessage("Evento Editado...", null, FacesMessage.SEVERITY_INFO);
            meeting = new Meeting();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="CLOSE EVENT OPEN EVENT"> 
    public void closeEvent(Meeting meetingOfTable) throws Exception {
        System.out.println(meetingOfTable);
        meetingOfTable.setIdState(clazz.STATE(Clazz._STATE._NAME._MEETING_FINALIZAR_EVENTO, Clazz._STATE._ENTITY._Meeting));
        meetingService.update(meetingOfTable);
        listMeeting = null;
    }

    public void openEvent(Meeting meetingOfTable) throws Exception {
        System.out.println(meetingOfTable);
        meetingOfTable.setIdState(clazz.STATE(Clazz._STATE._NAME._MEETING_SOLO_SOCIOS, Clazz._STATE._ENTITY._Meeting));
        meetingService.update(meetingOfTable);
        listMeeting = null;
    }
// </editor-fold> 

    /**
     * Para el agregado de los docentes que enseñaran en el evento
     *
     * @throws Exception
     */
    public void saveOrUpdateTeacher() throws Exception {
        if (teacher.getId() == null) {
            teacherService.save(teacher);
            FacesUtil.addMessage("Guardado con éxito...", null, FacesMessage.SEVERITY_INFO);
            listTeacher.add(teacher);
            teacher = new Teacher();
        } else {
            teacherService.update(teacher);
        }
    }

    ///////////////////////////GETTER AND SETTER/////////////////////////
    // <editor-fold defaultstate="collapsed" desc="Generated Code"> 
    public List<Teacher> getListTeacher() throws Exception {
        if (listTeacher == null) {
            listTeacher = teacherService.list();
        }
        return listTeacher;
    }

    public void setTeacherService(ITeacherService teacherService) {
        this.teacherService = teacherService;
    }

    public void setClazz(Clazz clazz) {
        this.clazz = clazz;
    }

    public void setMeetingService(IMeetingService meetingService) {
        this.meetingService = meetingService;
    }

    public List<Meeting> getListMeeting() throws Exception {
        if (listMeeting == null) {
            listMeeting = meetingService.list();
        }
        return listMeeting;
    }

    public void setListMeeting(List<Meeting> listMeeting) {
        this.listMeeting = listMeeting;
    }

    public Meeting getMeeting() {
        return meeting;
    }

    public void setMeeting(Meeting meeting) {
        this.meeting = meeting;
    }

    public void setListTeacher(List<Teacher> listTeacher) {
        this.listTeacher = listTeacher;
    }

    public Teacher getTeacher() {
        return teacher;
    }

    public Integer getActiveForUsers() {
        return activeForUsers;
    }

    public void setActiveForUsers(Integer activeForUsers) {
        this.activeForUsers = activeForUsers;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    public List<State> getListStateMeeting() throws Exception {
        if (listStateMeeting == null) {
            listStateMeeting = stateService.listHQL("from State s where "
                    + "s.entityName='" + Clazz._STATE._ENTITY._Meeting + "'");
            if (listStateMeeting.isEmpty()) {
                listStateMeeting.add(clazz.STATE(Clazz._STATE._NAME._MEETING_SOLO_SOCIOS, Clazz._STATE._ENTITY._Meeting));
                listStateMeeting.add(clazz.STATE(Clazz._STATE._NAME._MEETING_SOCIOS_Y_PERSONAS, Clazz._STATE._ENTITY._Meeting));
                listStateMeeting.add(clazz.STATE(Clazz._STATE._NAME._MEETING_FINALIZAR_EVENTO, Clazz._STATE._ENTITY._Meeting));
            }
        }
        return listStateMeeting;
    }

    public IStateService getStateService() {
        return stateService;
    }

    public void setStateService(IStateService stateService) {
        this.stateService = stateService;
    }

    public void setListStateMeeting(List<State> listStateMeeting) {
        this.listStateMeeting = listStateMeeting;
    }
// </editor-fold> 

// </editor-fold> 
}
